use yew::{function_component, html, use_state, Callback, Html, Properties};

#[derive(Clone, PartialEq)]
pub struct TreeNode {
    pub id: usize,
    pub label: String,
    pub children: Vec<TreeNode>,
    pub expanded: bool, // Toggle visibility
}

#[derive(Properties, PartialEq)]
pub struct TreeProps {
    pub node: TreeNode,
    pub on_toggle: Callback<usize>, // Handles expand/collapse
}

#[function_component]
fn TreeNodeComponent(props: &TreeProps) -> Html {
    let node = props.node.clone();
    
    let toggle = {
        let on_toggle = props.on_toggle.clone();
        move |_| on_toggle.emit(node.id)
    };

    html! {
        <li>
            <div onclick={toggle} class="node-label">
                { if !node.children.is_empty() {
                    if node.expanded { "▼ " } else { "► " }
                } else { "• " }}
                { &node.label }
            </div>
            { if node.expanded && !node.children.is_empty() {
                html! {
                    <ul class="nested">
                        { for node.children.into_iter().map(|child| {
                            html! { <TreeNodeComponent node={child} on_toggle={props.on_toggle.clone()} /> }
                        })}
                    </ul>
                }
            } else { html!{} }}
        </li>
    }
}


#[function_component]
pub fn Tree() -> Html {
    let tree = use_state(|| initial_tree_data()); // Your tree data generator

    let on_toggle = {
        let tree = tree.clone();
        Callback::from(move |id: usize| {
            let mut new_tree = (*tree).clone();
            toggle_node(&mut new_tree, id); // Implement logic to toggle node.expanded
            tree.set(new_tree);
        })
    };

    html! {
        <ul class="tree">
            <TreeNodeComponent node={(*tree).clone()} on_toggle={on_toggle} />
        </ul>
    }
}

fn initial_tree_data() -> TreeNode {
    TreeNode {
        id: 0,
        label: "demo1".to_string(),
        children: vec![],
        expanded: false,
    }
}

fn toggle_node(node: &mut TreeNode, _id: usize) {
    node.expanded = !node.expanded;
}